package cate.game.mail;

import cate.common.table.d.GDOperation;
import cate.game.GameBody;
import cate.game.mail.po.MailBuilder;
import cate.game.role.mail.Mail;
import cate.game.util.api.ConsoleApi;
import cp.solution.business.gm.BatchMailEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class BatchMailHandler {

    private MailManager parent;

    private GameBody getGame() {
        return parent.getGame();
    }

    public BatchMailHandler(MailManager parent) {
        this.parent = parent;
    }

    public void load(String msgFromConsole) {
        log.info("游戏服id={} 收到来自console的通知，通知游戏服去拉取属于自己游戏服的批量邮件。console是这么说的:“{}”", getGame().config.srvId, msgFromConsole);
        List<BatchMailEntity> bMails = ConsoleApi.queryBatchMail(getGame());
        if(bMails == null) {
            log.info("拉取到的bMails == null");
        } else if(bMails.isEmpty()) {
            log.info("拉取到的bMails.isEmpty()");
        } else {
            log.info("拉取到的邮件数量={}", bMails.size());
            int nd = ConsoleApi.deleteBatchMail(getGame());
            log.info("向console申请删除srvId={}的批量邮件, 删除数量={}", getGame().config.srvId, nd);
            int n = 0;
            for(BatchMailEntity bm : bMails) {
                log.info("批量邮件：{}", bm);
                Mail mail = new MailBuilder()
                        .setTitle(bm.getMailTitle())
                        .setContent(bm.getMailContent())
                        .setRewardConf(bm.getMailReward())
                        .setOperation(GDOperation.BATCH_MAIL)
                        .setOperationSub(bm.getBatchIndex()) //运行顺利的话，这个批次号名存实亡了
                        .build();
                getGame().mail.send(bm.getRoleId(), mail);
            }
        }
    }
}
